package org.example.zuul.http;

import java.io.IOException;
import java.util.Collection;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.example.zuul.filter.ZuulFilter;
import org.example.zuul.filter.ZuulProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ZuulServlet extends HttpServlet {
    private static final Logger LOGGER = LoggerFactory.getLogger(ZuulServlet.class);
    private final ZuulRunner zuulRunner = new ZuulRunner();

    @Override
    public void init(ServletConfig config) throws ServletException {
        super.init(config);
        @SuppressWarnings("unchecked")
        Collection<ZuulProperties.ZuulRoute> routes = (Collection<ZuulProperties.ZuulRoute>) config.getServletContext().getAttribute(ZuulFilter.ROUTES);
        zuulRunner.init(routes);
    }

    @Override
    public void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        zuulRunner.routeInit(req, resp);
        try {
            // 执行前置过滤
            zuulRunner.preRoute();
            // 执行过滤
            zuulRunner.route();
            // 执行后置过滤
            zuulRunner.postRoute();
        } catch (Exception e) {
            LOGGER.error("zuul service exception", e);
            RequestContext.getCurrentContext().getResponse().sendError(HttpServletResponse.SC_NOT_FOUND, e.getMessage());
        } finally {
            RequestContext.getCurrentContext().unset();
        }
    }
}
